package com.farah.lease.web.admin.service.impl;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.farah.lease.common.aliOss.AliOssProperties;
import com.farah.lease.web.admin.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private AliOssProperties properties;
    @Override
    public String upload(MultipartFile file)
    {
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(properties.getEndpoint(), properties.getAccessKeyId(), properties.getAccessKeySecret());
        String url = "";
        try {
            String filename=new SimpleDateFormat("yyyyMMdd").format(new Date())+"/"+ UUID.randomUUID()+"-"+file.getOriginalFilename();//文件名
            PutObjectRequest put = new PutObjectRequest(properties.getBucketName(), filename, file.getInputStream());
            PutObjectResult result = ossClient.putObject(put);
            url = "https://" + properties.getBucketName() + "." + properties.getEndpoint().substring(properties.getEndpoint().lastIndexOf("/") + 1) + "/" + filename;
            return url;
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
            return "";
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
